<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="null">
    <meta name="keyword" content="null">
    <meta name="theme-color" content="#600090">
    <meta name="msapplication-navbutton-color" content="#600090">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="#600090">
    <link rel="shortcut icon" href="/assets/favicon.ico">
    <link rel="alternate" type="application/atom+xml" title="张小阳" href="/atom.xml">
    <link rel="stylesheet" href="https://cdn.bootcss.com/animate.css/3.5.2/animate.css">
    <link rel="stylesheet" href="https://cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.css">
    <title>
        
        Review深入理解Javascript系列(三)｜MillZhang&#39;s blog
        
    </title>

    <link rel="canonical" href="http://millzhang.github.io/2017/06/15/2017-note/16.深入理解javascript-50-3/">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <!-- Custom CSS -->
    <link rel="stylesheet" href="/css/blog-style.css">

    <!-- Pygments Github CSS -->
    <link rel="stylesheet" href="/css/syntax.css">
</head>

<!-- hack iOS CSS :active style -->
<body ontouchstart="" class="animated fadeIn">
<!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top " id="nav-top" data-ispost = "true" data-istags="false
" data-ishome = "false" >
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header page-scroll">
            <button type="button" class="navbar-toggle">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand animated pulse" href="/">
                <span class="brand-logo">
                    MillZhang
                </span>
            </a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <!-- Known Issue, found by Hux:
            <nav>'s height woule be hold on by its content.
            so, when navbar scale out, the <nav> will cover tags.
            also mask any touch event of tags, unfortunately.
        -->
        <!-- /.navbar-collapse -->
        <div id="huxblog_navbar">
            <div class="navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li>
                        <a href="/"><i class="fa fa-home"></i>主页</a>
                    </li>
                   <li>
                        <a href="/tags"><i class="fa fa-tags"></i>归档</a>
                    </li>
                    <li>
                        <a href="/about"><i class="fa fa-user"></i>关于</a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <!-- /.container -->
</nav>
<script>
    // Drop Bootstarp low-performance Navbar
    // Use customize navbar with high-quality material design animation
    // in high-perf jank-free CSS3 implementation
//    var $body   = document.body;
    var $toggle = document.querySelector('.navbar-toggle');
    var $navbar = document.querySelector('#huxblog_navbar');
    var $collapse = document.querySelector('.navbar-collapse');

    $toggle.addEventListener('click', handleMagic)
    function handleMagic(e){
        if ($navbar.className.indexOf('in') > 0) {
        // CLOSE
            $navbar.className = " ";
            // wait until animation end.
            setTimeout(function(){
                // prevent frequently toggle
                if($navbar.className.indexOf('in') < 0) {
                    $collapse.style.height = "0px"
                }
            },400)
        }else{
        // OPEN
            $collapse.style.height = "auto"
            $navbar.className += " in";
        }
    }
</script>

<!-- Main Content -->

<!--only post-->

<header class="intro-header">
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 text-center">
                <div class="post-heading">
                    <h1>Review深入理解Javascript系列(三)</h1>
                    
                    <h2 class="subheading">解析Module模式</h2>
                    
                    <span class="meta">
                         作者 MillZhang
                        <span>
                          日期 2017-06-15
                         </span>
                    </span>
                    <div class="tags text-center">
                        
                        <a class="tag" href="/tags/#javascript"
                           title="javascript">javascript</a>
                        
                        <a class="tag" href="/tags/#深入理解Javascript系列"
                           title="深入理解Javascript系列">深入理解Javascript系列</a>
                        
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="post-title-haojen">
        <span>
            Review深入理解Javascript系列(三)
        </span>
    </div>
    <div class="post-header-image">
        
            <img src="http://oritfw5nq.bkt.clouddn.com/wall-303.jpg?imageView2/0/format/jpg/interlace/1/q/85|watermark/2/text/QnkgTWlsbHpoYW5n/font/5b6u6L2v6ZuF6buR/fontsize/480/fill/I0ZERkRGRA==/dissolve/56/gravity/SouthEast/dx/10/dy/10|imageslim">
         
    </div>
</header>

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">
            <!-- Post Container -->
            <div class="col-lg-8 col-lg-offset-1 col-sm-9 post-container">
                <h3 id="Module模式的基本特征"><a href="#Module模式的基本特征" class="headerlink" title="Module模式的基本特征"></a><code>Module</code>模式的基本特征</h3><ul>
<li>模块化,可重用</li>
<li>封装,不污染全局的命名空间</li>
<li>方法私有化,只暴露<code>public</code>方法</li>
</ul>
<h3 id="简单实现"><a href="#简单实现" class="headerlink" title="简单实现"></a>简单实现</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> <span class="built_in">module</span> = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">    <span class="comment">//声明私有成员变量</span></div><div class="line">    <span class="keyword">var</span> square = <span class="function"><span class="keyword">function</span>(<span class="params">x</span>)</span>&#123;</div><div class="line">        <span class="keyword">return</span> x*x;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">//暴露的是公开的成员</span></div><div class="line">    <span class="keyword">return</span> &#123;</div><div class="line">        <span class="attr">add</span>:<span class="function"><span class="keyword">function</span>(<span class="params">x,y</span>)</span>&#123;</div><div class="line">            <span class="keyword">return</span> square(x)+y;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">//调用</span></div><div class="line"><span class="keyword">var</span> m = <span class="keyword">new</span> <span class="built_in">module</span>();</div><div class="line"><span class="built_in">console</span>.log(m.add(<span class="number">2</span>,<span class="number">3</span>));<span class="comment">//7</span></div></pre></td></tr></table></figure>
<blockquote>
<p><a href="http://jsbin.com/bocodor/edit?js,console" target="_blank" rel="external">http://jsbin.com/bocodor/edit?js,console</a></p>
</blockquote>
<h3 id="匿名闭包"><a href="#匿名闭包" class="headerlink" title="匿名闭包"></a>匿名闭包</h3><p>两种声明匿名闭包的方式:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//第一种,推荐</span></div><div class="line">(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;())</div><div class="line"><span class="comment">//第二种</span></div><div class="line">(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;)()</div></pre></td></tr></table></figure>
<h3 id="匿名闭包与全局变量"><a href="#匿名闭包与全局变量" class="headerlink" title="匿名闭包与全局变量"></a>匿名闭包与全局变量</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">(<span class="function"><span class="keyword">function</span>(<span class="params">jQuery,Yahoo</span>)</span>&#123;</div><div class="line"> <span class="comment">//这里，我们的代码就可以使用全局的jQuery对象了，YAHOO也是一样</span></div><div class="line">&#125;(jQuery,Yahoo))</div></pre></td></tr></table></figure>
<p>通过匿名闭包的返回值来返回这个全局变量(匿名闭包的基本模式):</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> Car = (<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">    <span class="keyword">var</span> obj=&#123;&#125;,name=<span class="string">"CAR A"</span>;</div><div class="line">    obj.name = name;</div><div class="line">    obj.go = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">        <span class="built_in">console</span>.log(<span class="keyword">this</span>.name+<span class="string">'starts to go'</span>);</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> obj;</div><div class="line">&#125;());</div><div class="line"></div><div class="line"><span class="built_in">console</span>.log(Car.go())</div></pre></td></tr></table></figure>
<blockquote>
<p><a href="http://jsbin.com/tikesu/edit?js,console" target="_blank" rel="external">http://jsbin.com/tikesu/edit?js,console</a></p>
</blockquote>
<h3 id="Module模式将功能拆分多个文件的方式-协同开发"><a href="#Module模式将功能拆分多个文件的方式-协同开发" class="headerlink" title="Module模式将功能拆分多个文件的方式-协同开发"></a>Module模式将功能拆分多个文件的方式-协同开发</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> Car =(<span class="function"><span class="keyword">function</span>(<span class="params">obj</span>)</span>&#123;</div><div class="line">    obj.flameout=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">        <span class="built_in">console</span>.log(<span class="keyword">this</span>.name+<span class="string">'has to flameout...'</span>);</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> obj;</div><div class="line">&#125;(Car))</div></pre></td></tr></table></figure>
<blockquote>
<p><a href="http://jsbin.com/tikesu/edit?js,console" target="_blank" rel="external">http://jsbin.com/tikesu/edit?js,console</a></p>
</blockquote>
<h3 id="松耦合扩展"><a href="#松耦合扩展" class="headerlink" title="松耦合扩展"></a>松耦合扩展</h3><p>上述代码的不足就是,必须首先声明<code>Car</code>模块,确保加载顺序不能出错,改进:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> Car = (<span class="function"><span class="keyword">function</span>(<span class="params">obj</span>)</span>&#123;</div><div class="line">    <span class="keyword">return</span> obj;</div><div class="line">&#125;(Car || &#123;&#125;));</div></pre></td></tr></table></figure>
<p>通过这样的代码，每个单独分离的文件都保证这个结构，那么我们就可以实现任意顺序的加载，所以，这个时候的var就是必须要声明的，因为不声明，其它文件读取不到哦。</p>
<h3 id="紧耦合扩展"><a href="#紧耦合扩展" class="headerlink" title="紧耦合扩展"></a>紧耦合扩展</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> Car = (<span class="function"><span class="keyword">function</span> (<span class="params">obj</span>) </span>&#123;</div><div class="line">    <span class="comment">//拷贝一份需要重载的方法</span></div><div class="line">    <span class="keyword">var</span> oldGo = my.go;</div><div class="line"></div><div class="line">    my.go = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</div><div class="line">        <span class="comment">// 重载方法，依然可通过oldGo调用旧的方法</span></div><div class="line">    &#125;;</div><div class="line"></div><div class="line">    <span class="keyword">return</span> obj;</div><div class="line">&#125; (Car));</div></pre></td></tr></table></figure>
<p>紧耦合限制了加载顺序,但提供了可重载方法的机会.</p>
<h3 id="跨文件共享私有对象"><a href="#跨文件共享私有对象" class="headerlink" title="跨文件共享私有对象"></a>跨文件共享私有对象</h3><p>个人认为这是一个噱头,如果是协同开发同一个模块不同的多个文件的话可能也许会用到,但无疑这样的模块是庞大的.简单点的项目,可以相互约定私有属性.这边提供的方法,简单的说就是提供了一个私有属性项目访问开启和关闭的方法:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line">var Car = (function(my)&#123;</div><div class="line">    var _private = my._private = my._private || &#123;&#125;,</div><div class="line">    //该模块加载完成,即可调用_seal()进行私有属性的上锁.</div><div class="line">    _seal = my._seal = my._seal || function () &#123;</div><div class="line">        delete my._private;</div><div class="line">        delete my._seal;</div><div class="line">        delete my._unseal;</div><div class="line"></div><div class="line">    &#125;,</div><div class="line">    //开启访问</div><div class="line">    _unseal = my._unseal = my._unseal || function () &#123;</div><div class="line">        my._private = _private;</div><div class="line">        my._seal = _seal;</div><div class="line">        my._unseal = _unseal;</div><div class="line">    &#125;;</div><div class="line"></div><div class="line">    return my;</div><div class="line">&#125;(Car));</div></pre></td></tr></table></figure>
<h3 id="子模块"><a href="#子模块" class="headerlink" title="子模块"></a>子模块</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">Car.son = (function()&#123;</div><div class="line">    var son = &#123;&#125;;</div><div class="line">    return son;</div><div class="line">&#125;());</div></pre></td></tr></table></figure>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p><code>Module</code>模式就是基于<strong>匿名闭包</strong>的一个独立作用空间,对外可引用全局变量,对内可扩展私有属性和私有方法,开发模式效率高,代码量少,且可扩展性好.但初始化的时间消耗还是有点的,不过相对来说这样的开销是值得的.<br>使用好<code>Module</code>模式还是很有必要的!</p>

                <hr>
                <ul class="pager">
                    
                    <li class="previous">
                        <a href="/2017/06/19/2017-note/17.深入理解javascript-50-4/" data-toggle="tooltip" data-placement="top"
                           title="Review深入理解Javascript系列(四)">&larr; 上一页</a>
                    </li>
                    
                    
                    <li class="next">
                        <a href="/2017/06/15/2017-note/15.深入理解javascript-50-2/" data-toggle="tooltip" data-placement="top"
                           title="Review深入理解Javascript系列(二)">下一页 &rarr;</a>
                    </li>
                    
                </ul>
                <div class="comment">
                    <div id="cloud-tie-wrapper" class="cloud-tie-wrapper"></div>
                </div>
            </div>
            <div class="hidden-xs col-sm-3 toc-col">
                <div class="toc-wrap">
                    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#Module模式的基本特征"><span class="toc-text">Module模式的基本特征</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#简单实现"><span class="toc-text">简单实现</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#匿名闭包"><span class="toc-text">匿名闭包</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#匿名闭包与全局变量"><span class="toc-text">匿名闭包与全局变量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Module模式将功能拆分多个文件的方式-协同开发"><span class="toc-text">Module模式将功能拆分多个文件的方式-协同开发</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#松耦合扩展"><span class="toc-text">松耦合扩展</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#紧耦合扩展"><span class="toc-text">紧耦合扩展</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#跨文件共享私有对象"><span class="toc-text">跨文件共享私有对象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#子模块"><span class="toc-text">子模块</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#总结"><span class="toc-text">总结</span></a></li></ol>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Sidebar Container -->

            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container">

                <!-- Featured Tags -->
                

                <!-- Friends Blog -->
                
            </div>
        </div>

    </div>
</article>
<!-- 网易云音乐-->

<iframe class="cloud-music" frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 
    src="//music.163.com/outchain/player?type=2&amp;id=18803411&amp;auto=0&amp;height=66">
</iframe>
<!-- 网易云跟帖-->
<script src="https://img1.cache.netease.com/f2e/tie/yun/sdk/loader.js"></script>
<script>
var cloudTieConfig = {
  url: document.location.href, 
  sourceId: "",
  productKey: "40a8ee22b6084862a8907e6902e525fa",
  target: "cloud-tie-wrapper"
};
var yunManualLoad = true;
Tie.loader("aHR0cHM6Ly9hcGkuZ2VudGllLjE2My5jb20vcGMvbGl2ZXNjcmlwdC5odG1s", true);
</script>

<!-- Footer -->
<!-- Footer -->
<footer>
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 text-center">
                <p class="copyright text-muted">
                    Copyright &copy; MillZhang 2017
                    <br>
                </p>
            </div>
        </div>
    </div>
</footer>

<!-- jQuery -->
<script src="/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>

<!-- Custom Theme JavaScript -->
<script src="/js/blog.js"></script>

<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>

<!-- jquery.tagcloud.js -->
<script>
    // only load tagcloud.js in tag.html
    if($('#tag_cloud').length !== 0){
        async("http://oritfw5nq.bkt.clouddn.com/jquery.tagcloud.js",function(){
            $.fn.tagcloud.defaults = {
                //size: {start: 1, end: 1, unit: 'em'},
                color: {start: '#bbbbee', end: '#0085a1'},
            };
            $('#tag_cloud a').tagcloud();
        })
    }
</script>

<!--fastClick.js -->
<script>
    async("//cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
        var $nav = document.querySelector("nav");
        if($nav) FastClick.attach($nav);
    })
</script>



<!--wechat title img-->
<img class="wechat-title-img" src="http://oritfw5nq.bkt.clouddn.com/avatar.jpg?imageslim">
<a id="backtop" class="border-bottom" href="javascript:;">回顶部</a>
<script type="application/javascript">
var docOuter = document.body.scrollTop ? document.body : document.documentElement;
var backToTop = function(rate) {
  var doc = document.body.scrollTop ? document.body : document.documentElement;
  var scrollTop = doc.scrollTop;
  var top = function() {
    scrollTop = scrollTop + (0 - scrollTop) / (rate || 2);
    if (scrollTop < 1) {
      doc.scrollTop = 0;
      return;
    }
    doc.scrollTop = scrollTop;
    // 动画gogogo!
    requestAnimationFrame(top);
  };
  top();
};
var topBtn = document.getElementById('backtop'),
    docTop = docOuter.scrollTop;
if(docTop>=300){
  topBtn.style.opacity = 1;
}

topBtn.onclick = function() {
  backToTop(12)
}
window.onscroll = function(e) {
  var doc = document.body.scrollTop ? document.body : document.documentElement;
  var scrollTop = doc.scrollTop;
  if (scrollTop >= 300) {
    topBtn.style.opacity = 1;
  } else {
    topBtn.style.opacity = 0;
  }
}
</script>
</body>

</html>
